package com.xg.java.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xg.java.entity.FileShare;
import com.xg.java.entity.NetworkPan;
import com.xg.java.mapper.FileShareMapper;
import com.xg.java.mapper.NetworkPanMapper;
import com.xg.java.service.FileShareService;
import com.xg.java.util.CommonResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @description file_share服务层
 * @author wang
 * @date 2021-12-30
 */
@Service
public class FileShareServiceImpl extends ServiceImpl<FileShareMapper, FileShare> implements FileShareService {

    @Resource
    private NetworkPanMapper networkPanMapper;

    @Override
    @Transactional
    public Object extractFile(Long userId, String code) {
        FileShare fileShare = baseMapper.selectOne(new LambdaQueryWrapper<FileShare>().eq(FileShare::getCode, code));
        if(fileShare==null) return new CommonResult().failed("提取码不存在或已过期失效!!");
        NetworkPan networkPan = networkPanMapper.selectById(fileShare.getFileId());
        if (networkPan==null) return new CommonResult().failed("文件不存在或已删除!!");
        networkPan.setUserId(userId);
        networkPan.setPid(0L);
        if (networkPanMapper.insert(networkPan)>0){
            if (networkPan.getType()==1) {
                networkPanMapper.selectList(new LambdaQueryWrapper<NetworkPan>().eq(NetworkPan::getPid, fileShare.getFileId())).forEach(
                        a -> {
                            a.setPid(networkPan.getId());
                            a.setUserId(userId);
                            networkPanMapper.insert(a);
                        }
                );
            }
            return new CommonResult().success();
        }
        return new CommonResult().failed();
    }
}